package com.ctbri.gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.ctbri.util.SwingConsole;

class SquareRotate extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Rectangle2D square = new Rectangle2D.Float(-50f, -50f, 100f, 100f);
	private AffineTransform rot = new AffineTransform();
	private volatile int speed;
	private int boxSize;
	public SquareRotate() {
		setSpeed(5);
		setBoxSize(10);
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(!Thread.interrupted()) {
					SquareRotate.this.repaint();
					try{
						Thread.sleep(1000 / speed);
					} catch (InterruptedException e) {
						System.out.println("thread interrupted.");
					}
				}
			}
		}).start();
	}
	
	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		g2.translate(getWidth() / 2, getHeight() / 2);
		g2.scale(boxSize / 10.0, boxSize / 10.0);
		g2.setPaint(Color.blue);
		rot.rotate(Math.toRadians(20));
		g2.transform(rot);
		g2.draw(square);
	}
	
	public void setSpeed(int speed) {
		this.speed = speed;
	}
	public void setBoxSize(int boxSize) {
		this.boxSize = boxSize;
	}
}
public class Ex23 extends JFrame {
	private SquareRotate sq = new SquareRotate();
	private JSlider speedSlider = new JSlider(1, 10, 5);
	private JSlider sizeSlider = new JSlider(1, 20, 10);
	public Ex23() {
		add(sq);
		speedSlider.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				sq.setSpeed(speedSlider.getValue());
			}
		});
		sizeSlider.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				sq.setBoxSize(sizeSlider.getValue());
			}
		});
		JPanel sliders = new JPanel();
		sliders.setLayout(new GridLayout(2, 1));
		sliders.add(speedSlider);
		sliders.add(sizeSlider);
		add(sliders, BorderLayout.SOUTH);
		
	}
	public static void main(String[] args) {
		SwingConsole.run(new Ex23(), 400, 400);
	}

}
